<script>
import { reactive } from "vue";
import { getDicMap } from "@/utils/storage";
import { useTzRouter } from "@/vhooks/useTzRouter";
import {
  useReceiveForm,
  consignorInvalida,
  consigneeInvalida,
} from "./useReceiveForm";
import { useGoodsForms, fetchPackUnitData } from "./useGoodsForms";
import { useHandleBtn } from "./useHandleBtn";
import Taro from "@tarojs/taro";
import { regCommonChar, getUserInfo, letgetDay } from "@/utils";

import { detailApi, getFeeAgreeVOByCustRegNoApi } from "./api";

export default {
  name: "CcrnHome",
  components: {},
  setup() {
    const { EventChannel, route } = useTzRouter();
    const dicMap = getDicMap();
    const state = reactive({
      formsDisabled: false, // 所有表单录入禁用
      showTransportForm: false, // 展示转运信息表单
      showApplyForm: false, // 展示申报信息表单
      hideHandleBtn: false, // 隐藏操作按钮
      underApply: false, // 处于申报页面
      // applyId: "", // 申报id
      ccrnId: "",
      baseForm: {
        depArrTime: letgetDay(0),
      },
      receiveForm: {}, // 收发货人信息
      goodsForms: [{}], // 货物信息
      applyInfo: {}, // 申报信息 只有在已经申报之后才会有数据
      feeInfo: {}, // 费用信息
    });

    const billStatusDic = {
      99: "错误",
      100: "草稿",
      120: "准备寄出",
      300: "寄出中",
      400: "传送至政府",
      600: "已过境",
      999: "未知",
    };

    const { userType } = getUserInfo();

    // =============== handle route ===============

    if (route.query?.ccrnId) {
      const id = route.query.ccrnId;
      state.ccrnId = id;
      Taro.showLoading({
        title: "加载中",
      });
      detailApi(id)
        .then((res) => {
          Taro.hideLoading();
          const resData = res.data;
          if ([120, 300, 400, 600].includes(+resData.status)) {
            // 全表单禁用
            state.formsDisabled = true;
            // 隐藏操作按钮
            state.hideHandleBtn = true;
            // 获取费用信息
            getFeeAgreeVOByCustRegNoApi().then((res) => {
              // balance 账户余额  combined 费目金额
              state.feeInfo = {
                balance: res.data.balance,
                combined: res.data.combined,
              };
            });
          }

          // base
          state.baseForm = {
            impExpMode: resData.impExpMode,
            depArrTime: resData.depArrTime,
            hkLicensePlate: resData.hkLicensePlate,
            workNumber: resData.workNumber,
          };
          // 收发件人
          state.receiveForm = {
            consigneeAddr: resData.consigneeAddr,
            consigneeCountryCode: resData.consigneeCountryCode,
            consigneeName: resData.consigneeName,
            consignorAddr: resData.consignorAddr,
            consignorCountryCode: resData.consignorCountryCode,
            consignorName: resData.consignorName,
          };
          // 货物信息
          state.goodsForms = resData.itemList;
          // 根据货物信息数量来初始化包装种类单位
          if (resData.itemList.length) {
            state.packUnitObjList = resData.itemList.map((item) =>
              fetchPackUnitData(item.packType)
            );
          }
          // 转运信息
          state.transhipmentInfo = resData.transhipmentInfo;

          // 申报信息
          state.applyInfo = {
            sendTime: resData.sendTime, // 申报时间
            status: billStatusDic[resData.status], // 单据状态
            statusCode: resData.status, // 单据状态
            senderName: resData.senderName, // 操作人
            ccrn: resData.ccrn,
          };
          // 缓存接口获取的数据
          state.detailData = resData;
        })
        .catch(() => {
          Taro.hideLoading();
        });
    }

    EventChannel.on(route.path, (event) => {
      if (event?.type === "transportBack") {
        // 转运信息数据返回
        state.transhipmentInfo = event.data;
      } else if (event?.type === "licenceBack") {
        // 许可证信息数据返回
        const { goodsIndex, licenceForms } = event.data;
        if (goodsIndex) {
          state.goodsForms[goodsIndex].permitsList = licenceForms;
          if (!licenceForms?.length) {
            delete state.goodsForms[goodsIndex].permitsList;
          }
        }
      } else if (event?.type === "consigner") {
        //发货人返回信息
        state.receiveForm.consignorName = event.data.name;
        state.receiveForm.consignorAddr = event.data.address;
        state.receiveForm.consignorCountryCode = event.data.countryCode;
      } else if (event?.type === "consignee") {
        //收货人返回信息
        state.receiveForm.consigneeName = event.data.name;
        state.receiveForm.consigneeAddr = event.data.address;
        state.receiveForm.consigneeCountryCode = event.data.countryCode;
      } else if (event?.type === "cargoCode") {
        //产品编号信息
        const {
          index: goodsIndex,
          cargoCode,
          packType,
          cargoDesc,
          packQuantity,
          packUnit,
        } = event.data;
        // 通过 种类 获取对应的单位字典
        state.packUnitObjList[goodsIndex] = fetchPackUnitData(packType);
        state.goodsForms[goodsIndex].cargoCode = cargoCode;
        state.goodsForms[goodsIndex].packType = packType;
        state.goodsForms[goodsIndex].cargoDesc = cargoDesc;
        state.goodsForms[goodsIndex].packQuantity = packQuantity;
        state.goodsForms[goodsIndex].packUnit = packUnit;
      }
    });

    // =============== validate ===============
    // 是否空字符串
    const isEmpty = (str) => {
      if (typeof str === "number") {
        str = str.toString();
      }
      return (
        str === null || str === undefined || str.trim() === "" || str === "null"
      );
    };

    // 验证表单数据
    const isValidate = () => {
      const { impExpMode, depArrTime } = state.baseForm;
      const {} = state.receiveForm;
      try {
        if (isEmpty(impExpMode)) {
          throw new Error("请输入进出类型");
        }
        if (isEmpty(depArrTime)) {
          throw new Error("请输入货运日期");
        }

        // 校验发货人
        if (consignorInvalida(state)) {
          throw new Error(consignorInvalida(state));
        }

        // 校验收货人
        if (consigneeInvalida(state)) {
          throw new Error(consigneeInvalida(state));
        }

        for (let i = 0; i < state.goodsForms.length; i++) {
          const {
            packType,
            cargoDesc,
            packQuantity,
            packUnit,
          } = state.goodsForms[i];
          if (isEmpty(packType)) {
            throw new Error("请选择种类");
          }
          if (isEmpty(cargoDesc)) {
            throw new Error("请输入货物说明");
          }
          if (isEmpty(packQuantity)) {
            throw new Error(`请输入${state.packUnitObjList[i].label}`);
          }
          if (isEmpty(packUnit)) {
            throw new Error(`请选择${state.packUnitObjList[i].title}`);
          }
        }
        return true;
      } catch (err) {
        $TzNotify.danger(err.message);
        return false;
      }
    };

    // =============== render ===============

    const wrapText = (dom, text) => {
      return !state.formsDisabled ? (
        dom
      ) : (
        <tz-text class="break-text">{text}</tz-text>
      );
    };

    // 收发货人信息
    const renderReceiveForm = useReceiveForm({
      state,
      dicMap,
      wrapText,
    });

    // 货物信息
    const renderGoodsForms = useGoodsForms({
      state,
      dicMap,
      isEmpty,
      wrapText,
    });

    // 费用信息
    const feeRender = () => {
      return (
        <tz-view class="form-block">
          <tz-form class="fee-form">
            <tz-cell title="账户余额" border>
              <tz-text>{state.feeInfo.balance}</tz-text>
            </tz-cell>
            <tz-cell title="无缝费用" border>
              <tz-text>{state.feeInfo.combined}</tz-text>
            </tz-cell>
          </tz-form>
        </tz-view>
      );
    };

    // 转运信息 仅作展示
    const transportRender = () => {
      return (
        <tz-view class="form-block">
          <tz-text class="form-block-title">转运信息</tz-text>
          <tz-form class="transport-form">
            <tz-cell title="多模式转运货物参考编号" border>
              <tz-text class="break-text">
                {state.transhipmentInfo.imtfRefNo}
              </tz-text>
            </tz-cell>
            <tz-cell title="运输方式" border required>
              <tz-text>
                {
                  dicMap.modeOfTransportList.filter(
                    (item) =>
                      item.code === state.transhipmentInfo.modeOfTransport
                  )[0].nameCn
                }
              </tz-text>
            </tz-cell>
            <tz-cell title="船名" border>
              <tz-text class="break-text">
                {state.transhipmentInfo.vessel}
              </tz-text>
            </tz-cell>
            <tz-cell title="航班(航次)号" border>
              <tz-text>{state.transhipmentInfo.convNo}</tz-text>
            </tz-cell>
            <tz-cell title="预计到达/出发日期" border required>
              <tz-text>{state.transhipmentInfo.estDepArrDt}</tz-text>
            </tz-cell>
            <tz-cell title="主提单编号" border required>
              <tz-text class="break-text">
                {state.transhipmentInfo.masterNo}
              </tz-text>
            </tz-cell>
            <tz-cell title="副提单编号" border>
              <tz-text class="break-text">
                {state.transhipmentInfo.houseNo}
              </tz-text>
            </tz-cell>
          </tz-form>
        </tz-view>
      );
    };

    // 申报信息 仅展示用
    const applyInfoRender = () => {
      let statusColor = "";
      if (["120", "300"].includes(state.applyInfo.statusCode)) {
        statusColor = "primary";
      } else if (["400", "600"].includes(state.applyInfo.statusCode)) {
        statusColor = "success";
      } else if (["99", "999"].includes(state.applyInfo.statusCode)) {
        statusColor = "danger";
      } else {
        statusColor = "info";
      }
      return (
        <tz-view class="form-block">
          <tz-text class="form-block-title">申报信息</tz-text>
          <tz-form class="apply-form">
            <tz-cell title="申报时间" border>
              <tz-text>{state.applyInfo.sendTime}</tz-text>
            </tz-cell>
            <tz-cell title="操作人员" border>
              <tz-text>{state.applyInfo.senderName}</tz-text>
            </tz-cell>
            <tz-cell
              class={["status-name", statusColor]}
              class="status"
              title="单据状态"
              border
            >
              <tz-text>{state.applyInfo.status}</tz-text>
            </tz-cell>
            <tz-cell title="CCRN" border>
              <tz-text>{state.applyInfo.ccrn}</tz-text>
            </tz-cell>
          </tz-form>
        </tz-view>
      );
    };

    // 按钮
    const renderHandleBtn = useHandleBtn({ state, isValidate });

    // =============== return ===============

    const handleimpExpModeChange = (e, rangeItem) => {
      if (rangeItem.para_value === "I") {
        // 大陆 → 香港
        state.receiveForm.consignorCountryCode = "CN";
        state.receiveForm.consigneeCountryCode = "HK";
      } else if (rangeItem.para_value === "E") {
        // 香港 → 大陆
        state.receiveForm.consignorCountryCode = "HK";
        state.receiveForm.consigneeCountryCode = "CN";
      }
    };
    // NOTE: 金额模块展示条件：个人账户-确认申报状态-存在金额数据
    return () => (
      <tz-view class="ccrn-home">
        <tz-view class="form-block">
          <tz-form class="base-form">
            <tz-cell title="进出类型" border required>
              <tz-picker
                v-model={state.baseForm.impExpMode}
                mode="selector"
                range={dicMap.ieTypeList}
                rangeKey="para_name"
                valueKey="para_value"
                disabled={state.formsDisabled}
                onChange={(e, rangeItem) =>
                  handleimpExpModeChange(e, rangeItem)
                }
              ></tz-picker>
            </tz-cell>
            <tz-cell title="货运日期" border required>
              <tz-picker
                disabled={state.formsDisabled}
                v-model={state.baseForm.depArrTime}
                mode="date"
              >
                <tz-view class="date-picker-slot">
                  <tz-text>
                    <text>{state.baseForm.depArrTime || "--请选择--"}</text>
                  </tz-text>
                  {!state.formsDisabled && (
                    <tz-icon class="tz-input-icon" name="calendar"></tz-icon>
                  )}
                </tz-view>
              </tz-picker>
            </tz-cell>
            <tz-cell title="香港车牌" border>
              <tz-input
                disabled={state.formsDisabled}
                v-model={state.baseForm.hkLicensePlate}
                type="text"
                placeholder={state.formsDisabled ? "" : "请输入香港车牌"}
                clearable
                maxlength="8"
                rules={(val) => {
                  const value =
                    val?.match(/[\w`~!@#$%&\^\/\u4e00-\u9fa5-]+/g)?.[0] || "";
                  return value.toUpperCase();
                }}
              />
            </tz-cell>
            <tz-cell title="工作单号" border>
              {wrapText(
                <tz-input
                  disabled={state.formsDisabled}
                  v-model={state.baseForm.workNumber}
                  type="text"
                  placeholder={state.formsDisabled ? "" : "请输入工作单号"}
                  clearable
                  maxlength="100"
                />,
                state.baseForm.workNumber
              )}
            </tz-cell>
          </tz-form>
        </tz-view>
        {renderReceiveForm}
        {renderGoodsForms}
        {state.showTransportForm && state.transhipmentInfo && transportRender()}
        {userType.isPersonal &&
          state.underApply &&
          state.feeInfo.balance &&
          feeRender()}
        {state.applyInfo.ccrn && applyInfoRender()}
        {!state.hideHandleBtn && renderHandleBtn}
      </tz-view>
    );
  },
};
</script>

<style lang="scss">
.ccrn-home {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  .form-block {
    width: 100%;
    display: flex;
    flex-direction: column;
    .form-block-title {
      padding: 13px 0 13px 21px;
      color: $title-color;
    }

    .goods-handle-area {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .goods-handle-btn {
        padding-right: 21px;
        .tz-button {
          width: 78px;
          height: 26px;
          background: #fff;
          &:first-child {
            margin-right: 5px;
          }
        }
      }
    }

    .goods-form {
      &:not(:first-child) {
        margin-top: 1px;
      }
      .tz-cell {
        .no {
          flex: 1;
        }
      }
    }

    .fee-form {
      .tz-cell-value {
        color: $danger-color;
      }
    }

    .transport-form {
      .tz-cell {
        line-height: unset;
        .tz-cell-label {
          padding: 13px 20px 13px 0;
        }
      }
    }

    .apply-form {
      .status-name {
        &.primary {
          color: $primary-color;
        }
        &.success {
          color: $success-color-end;
        }
        &.danger {
          color: $danger-color;
        }
        &.info {
          color: $info-color;
        }
      }
    }

    .tz-form {
      background-color: $white;
      .tz-cell {
        .tz-cell-label {
          text-align: right;
          padding-right: 20px;
        }
        .tz-cell-value {
          padding-right: 20px;
          .first-icon {
            padding: 10px;
            margin-right: 5px;
          }
          .tz-icon {
            font-size: 20px;
          }
        }
        // &:last-child:after {
        //   border: none;
        // }
        .tz-picker {
          .placeholder {
            color: $placeholder-color;
          }
          .date-picker-slot {
            display: flex;
            align-items: center;
            .tz-text {
              flex: 1;
            }
          }
        }
        .tz-icon-scan {
          color: $info-color-active;
        }
        &.arrow-cell {
          .tz-cell-value {
            // justify-content: flex-end;
            .tz-text {
              flex: 1;
            }
          }
        }

        .break-text {
          word-break: break-all;
          line-height: initial;
          padding: 10px 0;
        }
      }
    }
  }
  .btn-area {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 40px;
    .tz-button {
      align-self: center;
      width: 345px;
      height: 44px;
      margin-top: 20px;
    }
    .btn-wrap {
      display: flex;
      flex-direction: column;
      width: 345px;
      // 并列按钮
      &.abreast {
        flex-direction: row;
        justify-content: space-between;
        .tz-button {
          width: 45%;
        }
      }
    }
  }
}
</style>
